<template>
  <UserModal
    :visible="visibleModal"
    :mode="modalMode"
    :user="user"
    @close="closeModal"
    @save="onSave"
  />
  <div class="user-management-container">
    <a-card class="management-card" :bordered="false">
      <!-- 增强型搜索栏 -->
      <!-- 搜索栏 -->
      <div class="search-bar">
        <a-input-search
          v-model="searchParams.userName"
          placeholder="请输入用户名或账号"
          @search="handleSearch"
          @press-enter="handleSearch"
          class="search-input"
          allow-clear
        >
          <template #prefix>
            <icon-search />
          </template>
        </a-input-search>
      </div>

      <!-- 高级用户表格 -->
      <div class="table-wrapper">
        <a-table
          :data="userList"
          :pagination="{
            showTotal: true,
            pageSize: searchParams.pageSize,
            current: searchParams.current,
            total,
            showPageSize: true,
          }"
          :loading="loading"
          @page-change="handlePageChange"
          @page-size-change="onPageSizeChange"
          class="premium-table"
          row-key="id"
          :scroll="{ x: 1160, y: 560 }"
        >
          <template #columns>
            <!-- 头像列 -->
            <a-table-column title="头像" :width="90">
              <template #cell="{ record }">
                <div class="avatar-wrapper">
                  <a-avatar :size="44" class="user-avatar">
                    <img
                      v-if="record.userAvatar"
                      :src="record.userAvatar"
                      alt="avatar"
                    />
                    <icon-user v-else class="default-avatar" />
                  </a-avatar>
                  <div v-if="record.userStatus" class="online-badge"></div>
                </div>
              </template>
            </a-table-column>

            <!-- 用户名 -->
            <a-table-column title="用户名" :width="140">
              <template #cell="{ record }">
                <div class="username-cell">
                  <span class="username-text">{{ record.userName }}</span>
                  <icon-edit
                    class="edit-icon"
                    @click="handleEditUsername(record)"
                  />
                </div>
              </template>
            </a-table-column>

            <!-- 账号信息 -->
            <a-table-column title="账号" :width="160">
              <template #cell="{ record }">
                <div class="account-cell">
                  <icon-user class="account-icon" />
                  <span class="account-text">{{ record.userAccount }}</span>
                </div>
              </template>
            </a-table-column>

            <!-- 个人简介 -->
            <!-- <a-table-column title="个人简介" :width="300">
              <template #cell="{ record }">
                <div class="bio-content">
                  <div class="bio-text">
                    {{ record.userProfile || "暂无个人介绍" }}
                  </div>
                  <div v-if="record.userProfile?.length > 60" class="read-more">
                    ...
                  </div>
                </div>
              </template>
            </a-table-column> -->

            <!-- 用户角色 -->
            <a-table-column title="角色" :width="100">
              <template #cell="{ record }">
                <div class="role-tag-wrapper">
                  <span
                    class="role-tag"
                    :style="{
                      backgroundColor: getRoleColor(record.userRole).bg,
                      color: getRoleColor(record.userRole).text,
                    }"
                  >
                    {{ record.userRole }}
                  </span>
                </div>
              </template>
            </a-table-column>

            <!-- 创建时间 -->
            <a-table-column title="创建时间" :width="180">
              <template #cell="{ record }">
                <div class="timestamp">
                  <icon-clock-circle class="time-icon" />
                  <span class="time-text">
                    {{
                      moment(record.createTime).format("YYYY-MM-DD HH:mm")
                    }}</span
                  >
                </div>
              </template>
            </a-table-column>

            <!-- 操作列 -->
            <a-table-column title="操作" :width="150" fixed="right">
              <template #cell="{ record }">
                <div class="action-buttons">
                  <a-tooltip content="查看详情">
                    <a-button
                      type="text"
                      class="view-btn"
                      @click="handleView(record)"
                    >
                      <icon-eye />
                    </a-button>
                  </a-tooltip>
                  <a-tooltip content="编辑信息">
                    <a-button
                      v-if="record.userRole === 'user'"
                      type="text"
                      class="edit-btn"
                      @click="handleEdit(record)"
                    >
                      <icon-edit />
                    </a-button>
                  </a-tooltip>
                  <a-tooltip content="删除用户">
                    <a-button
                      v-if="record.userRole === 'user'"
                      type="text"
                      class="delete-btn"
                      @click="handleDelete(record)"
                    >
                      <icon-delete />
                    </a-button>
                  </a-tooltip>
                </div>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { IconEye, IconEdit, IconDelete } from "@arco-design/web-vue/es/icon";
import { UserControllerService } from "../../../generated";
import { ref, onMounted } from "vue";
import { UserListVO } from "../../../generated/models/UserListVO";
import moment from "moment";
import { Message, Modal } from "@arco-design/web-vue";
import UserModal from "@/components/UserModel.vue";
// 原有脚本逻辑保持不变，新增角色颜色配置
const roleColors: Record<string, { bg: string; text: string }> = {
  admin: { bg: "#fff1f0", text: "#cf1322" },
  user: { bg: "#f6ffed", text: "#389e0d" },
  guest: { bg: "#e6f7ff", text: "#096dd9" },
  vip: { bg: "#f9f0ff", text: "#531dab" },
};

const total = ref(0);
const searchParams = ref({
  userName: "",
  pageSize: 10,
  current: 1,
});
const loadData = async () => {
  console.log("加载数据");
  const res = await UserControllerService.getUserListUsingPost("", {
    pageSize: searchParams.value.pageSize,
    current: searchParams.value.current,
    account: searchParams.value.userName,
    userName: searchParams.value.userName,
  });
  console.log(res);
  userList.value = res.data.userListVOList;
  total.value = res.data.total;
  loading.value = false;
};
onMounted(() => {
  console.log("用户管理");
  loadData();
});
const loading = ref(true);
const getRoleColor = (role: string) => {
  return roleColors[role.toLowerCase()] || { bg: "#f5f5f5", text: "#595959" };
};
const userList = ref([
  {
    createTime: "2025-02-03T18:14:26.000+00:00",
    userAccount: "1234567",
    userAvatar:
      "https://yyda-1333102418.cos.ap-beijing.myqcloud.com/user_avatar/1886478365837283329/jvKO32Yw-微信图片_20241213003008.jpg",
    userId: "1886478365837283329",
    userName: "一个程序员",
    userProfile: "嘿嘿",
    userRole: "user",
    userStatus: false,
  },
] as UserListVO);
const visibleModal = ref(false);
const modalMode = ref<"view" | "edit">("view");
const user = ref({
  createTime: "2025-02-03T18:14:26.000+00:00",
  userAccount: "1234567",
  userAvatar:
    "https://yyda-1333102418.cos.ap-beijing.myqcloud.com/user_avatar/1886478365837283329/jvKO32Yw-微信图片_20241213003008.jpg",
  userId: "1886478365837283329",
  userName: "一个程序员",
  userProfile: "嘿嘿",
  userRole: "user",
  userStatus: false,
});
// 打开弹窗，mode 用于指定打开的模式
const openModal = (mode: "view" | "edit") => {
  modalMode.value = mode;
  visibleModal.value = true;
};

// 关闭弹窗
const closeModal = () => {
  visibleModal.value = false;
  loadData();
};
// 监听保存事件，当编辑用户数据后触发
const onSave = async (updatedUser: typeof user.value) => {
  // 这里可以做数据更新或者发送请求保存数据
  console.log("更新后的用户数据：", updatedUser);
  user.value = { ...updatedUser };
  const res = await UserControllerService.adminEditUserUsingPost("", {
    userId: user.value.userId,
    userName: user.value.userName,
    userProfile: user.value.userProfile,
  });
  if (res.code === 0) {
    Message.success("更新成功");
    closeModal();
  } else {
    Message.error("更新失败");
  }
};
const handleView = (record: any) => {
  console.log("查看详情", record);
  user.value = { ...record };
  openModal("view");
};
const handleEdit = (record: any) => {
  console.log("编辑用户", record);
  user.value = { ...record };
  openModal("edit");
};
const handleDelete = (record: any) => {
  console.log("删除用户", record);
  Modal.warning({
    title: "确定删除吗？",
    content: "点击确定按钮将删除该用户，其他地方取消删除",
    okText: "确定",
    cancelText: "取消",
    onOk: () => {
      doDelete(record.userId);
    },
  });
};
const doDelete = async (userId: number) => {
  console.log("删除用户", userId);
  const res = await UserControllerService.deleteUserUsingDelete("", userId);
  Message.success("删除成功");
  console.log(res);
  loadData();
};
const handleSearch = (value: string) => {
  console.log("搜索关键词", value);
  loadData();
};
const handlePageChange = (page: number) => {
  console.log("分页改变", page);
  searchParams.value.current = page;
  loadData();
};
const onPageSizeChange = (pageSize: number) => {
  console.log("分页大小改变", pageSize);
  searchParams.value.pageSize = pageSize;
  loadData();
};
const handleEditUsername = (record: any) => {
  console.log("编辑用户名", record);
};

// const getRoleColor = (role: string) => {
//   return roleColors[role.toLowerCase()] || { bg: "#f5f5f5", text: "#595959" };
// };
</script>

<style scoped>
.premium-table >>> .arco-table-th,
.premium-table >>> .arco-table-cell {
  text-align: center;
}
.user-management-container {
  padding: 24px;
  /* background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); */
  min-height: 100vh;
}

.management-card {
  border-radius: 16px;
  box-shadow: 0 12px 24px -6px rgba(0, 0, 0, 0.05),
    0 8px 16px -8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.management-card:hover {
  transform: translateY(-2px);
}

.enhanced-search-bar {
  padding: 16px 24px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.neo-search-input >>> .arco-input-wrapper {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

.neo-search-input >>> .arco-input-wrapper:hover {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.neo-search-input >>> .arco-input-wrapper:focus-within {
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
}

.search-icon {
  color: #8c8c8c;
  font-size: 16px;
  margin-right: 8px;
}

.search-shortcut {
  background: rgba(0, 0, 0, 0.04);
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 12px;
  color: #666;
  border: 1px solid #eee;
}

.premium-table >>> .arco-table-header {
  background: rgba(250, 250, 250, 0.95);
  backdrop-filter: blur(4px);
}
.table-wrapper {
  text-align: center;
  overflow-x: auto;
}
.premium-table {
  display: inline-block;
  min-width: 1160px; /* 或者设置为一个更大的数值 */
}
.premium-table >>> .arco-table-th {
  border-bottom: 2px solid #f0f0f0;
  font-weight: 600;
  color: #262626;
}

.premium-table >>> .arco-table-tr {
  transition: background 0.2s ease;
}

.premium-table >>> .arco-table-tr:hover {
  background: rgba(24, 144, 255, 0.02) !important;
}

.premium-table >>> .arco-table-tr:hover .username-text {
  color: #1890ff;
}

.premium-table >>> .arco-table-td {
  border-bottom: 1px solid rgba(0, 0, 0, 0.04);
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
}

.user-avatar {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.default-avatar {
  color: #8c8c8c;
}

.online-badge {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 10px;
  height: 10px;
  background: #52c41a;
  border: 2px solid #fff;
  border-radius: 50%;
}

.username-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username-text {
  font-weight: 500;
  transition: color 0.2s ease;
}

.edit-icon {
  color: #8c8c8c;
  cursor: pointer;
  opacity: 0;
  transition: all 0.2s ease;
}

.edit-icon:hover {
  color: #1890ff;
}

.username-cell:hover .edit-icon {
  opacity: 1;
}

.account-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.account-icon {
  color: #8c8c8c;
  font-size: 14px;
}

.account-text {
  font-family: "JetBrains Mono", monospace;
  color: #595959;
}

.bio-content {
  position: relative;
  line-height: 1.5;
  max-height: 4.5em;
  overflow: hidden;
}

.bio-text {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  white-space: pre-wrap;
  color: #595959;
}

.read-more {
  position: absolute;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, transparent, white 50%);
  padding-left: 20px;
  color: #8c8c8c;
  cursor: pointer;
}

.role-tag {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 14px;
  font-size: 12px;
  font-weight: 500;
  letter-spacing: 0.5px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.timestamp {
  display: flex;
  align-items: center;
  gap: 8px;
}
.search-bar {
  margin-bottom: 24px;
  max-width: 400px;
}

.time-icon {
  color: #8c8c8c;
  font-size: 14px;
}

.time-text {
  color: #595959;
  font-family: "JetBrains Mono", monospace;
}

.action-buttons {
  display: flex;
  gap: 8px;
  opacity: 0.8;
  transition: opacity 0.2s ease;
}

.action-buttons:hover {
  opacity: 1;
}

.view-btn {
  color: #8c8c8c;
}

.view-btn:hover {
  color: #1890ff;
  background: rgba(24, 144, 255, 0.1);
}

.edit-btn {
  color: #8c8c8c;
}

.edit-btn:hover {
  color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
}

.delete-btn {
  color: #8c8c8c;
}

.delete-btn:hover {
  color: #f5222d;
  background: rgba(245, 34, 45, 0.1);
}
</style>
